// 通用高亮编辑器组件 CodeEditor.tsx
import React, { useEffect, useRef } from 'react';
import Editor from '@monaco-editor/react';
import * as monacoCore from 'monaco-editor/esm/vs/editor/editor.api';
import { shikiToMonaco } from '@shikijs/monaco';
import { createHighlighter } from 'shiki';

interface CodeEditorProps {
  language: 'cpp' | 'java' | 'python';
  value: string;
  onChange: (val: string) => void;
  height?: string;
}

const CodeEditor: React.FC<CodeEditorProps> = ({ language, value, onChange, height = '400px' }) => {
  const highlighterLoaded = useRef(false);

  const handleEditorMount = async (editor: any, monaco: typeof monacoCore) => {
    if (highlighterLoaded.current) return;

    const highlighter = await createHighlighter({
      themes: ['vitesse-dark'],
      langs: ['cpp', 'java', 'python'],
    });

    monaco.languages.register({ id: 'cpp' });
    monaco.languages.register({ id: 'java' });
    monaco.languages.register({ id: 'python' });

    await shikiToMonaco(highlighter, monaco);
    monaco.editor.setTheme('vitesse-dark');

    highlighterLoaded.current = true;
  };

  return (
    <Editor
      height={height}
      language={language}
      value={value}
      onChange={(val:any) => onChange(val || '')}
      theme="vitesse-dark"
      onMount={handleEditorMount}
      options={{
        fontSize: 14,
        minimap: { enabled: false },
        scrollBeyondLastLine: false,
        automaticLayout: true,
        wordWrap: 'on',
      }}
    />
  );
};

export default CodeEditor;
